package com.example.myfultter

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.util.LruCache
import android.util.Log
import android.widget.ImageView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.net.HttpURLConnection
import java.net.URL

class MainActivity004 : AppCompatActivity() {
    private val imageUrl = "https://picsum.photos/600/600"
    private lateinit var imageView: ImageView

    companion object {
        private val imageCache: LruCache<String, Bitmap> by lazy {
            val maxMemoryKb = (Runtime.getRuntime().maxMemory() / 1024).toInt()
            val cacheSizeKb = maxMemoryKb / 8
            object : LruCache<String, Bitmap>(cacheSizeKb) {
                override fun sizeOf(key: String, value: Bitmap): Int {
                    return value.byteCount / 1024
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main004)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        
        imageView = findViewById(R.id.imageView3)
        findViewById<android.widget.Button>(R.id.button7).setOnClickListener { loadImage() }
        loadImage()
    }

    private fun loadImage() {
        lifecycleScope.launch(Dispatchers.IO) {
            imageCache.get(imageUrl)?.let { cached ->
                withContext(Dispatchers.Main) { imageView.setImageBitmap(cached) }
                return@launch
            }

            var conn: HttpURLConnection? = null
            try {
                var currentUrl = URL(imageUrl)
                var redirects = 0

                while (redirects < 5) {
                    conn = (currentUrl.openConnection() as HttpURLConnection).apply {
                        connectTimeout = 10_000
                        readTimeout = 10_000
                        instanceFollowRedirects = false
                        setRequestProperty("User-Agent", "Mozilla/5.0 (Android) Myfultter/1.0")
                    }

                    val code = conn.responseCode
                    Log.d("MainActivity004", "HTTP code=$code url=$currentUrl")

                    if (code in 300..399) {
                        val location = conn.getHeaderField("Location")
                        conn.disconnect()
                        if (location != null) {
                            currentUrl = URL(currentUrl, location)
                            redirects++
                            continue
                        } else {
                            Log.e("MainActivity004", "Redirect without Location header")
                            break
                        }
                    } else if (code == HttpURLConnection.HTTP_OK) {
                        val bitmap = conn.inputStream.buffered().use(BitmapFactory::decodeStream)
                        updateUI(bitmap)
                        bitmap?.let { imageCache.put(imageUrl, it) }
                        break
                    } else {
                        Log.e("MainActivity004", "Unexpected HTTP code: $code")
                        updateUI(null)
                        break
                    }
                }
            } catch (e: Exception) {
                Log.e("MainActivity004", "Load image failed", e)
                updateUI(null)
            } finally {
                conn?.disconnect()
            }
        }
    }

    private suspend fun updateUI(bitmap: Bitmap?) {
        withContext(Dispatchers.Main) {
            if (bitmap != null) {
                imageView.setImageBitmap(bitmap)
            } else {
                imageView.setImageResource(R.drawable.ic_launcher_background)
            }
        }
    }
}